package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QRY_A19;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QRF;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import com.herench.bunch.commons.utils.IdGenerator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;

public class LoadPrescriptionListConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {

        Document document = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.LOAD_PRESCRIPTION_LIST_CODE);
        Element requestElement = document.getRootElement();
        QRY_A19 hl7 = (QRY_A19) requestMessage.getHl7Message();
        QRF qrf = hl7.getQRF();

        String RegCode = qrf.getQrf1_WhereSubjectFilter(0).getValue();
        String HISPatientID = qrf.getQrf1_WhereSubjectFilter(1).getValue();


        requestElement.addElement("RegCode").addText(RegCode!=null?RegCode:"");
        requestElement.addElement("HISPatientID").addText(HISPatientID!=null?HISPatientID:"");

        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200230 from HIS XML = "+ message);
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        Element res = doc.getRootElement();
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        msa.getMsa6_ErrorCondition().getCe1_Identifier().setValue(res.elementTextTrim("IsSuccessed"));
        msa.getMsa6_ErrorCondition().getCe2_Text().setValue(res.elementTextTrim("ErrorMsg"));

        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
        Element Items = res.element("Items");

        int index = 0;
        for (Iterator<Element> iterator = Items.elementIterator(); iterator.hasNext(); ) {
            Element el = iterator.next();
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
            buffer.append("PrescriptionCode=").append(el.elementTextTrim("PrescriptionCode")).append("#")
                    .append("PrescriptionType=").append(el.elementTextTrim("PrescriptionType")).append("#")
                    .append("PrescriptionName=").append(el.elementTextTrim("PrescriptionName")).append("#")
                    .append("TotalAmount=").append(el.elementTextTrim("TotalAmount")).append("#")
                    .append("DrugMaker=").append(el.elementTextTrim("DrugMaker")).append("#")
                    .append("Diagnosis=").append(el.elementTextTrim("DrugSender")).append("#")
                    .append("OrderNum=").append(el.elementTextTrim("Diagnosis")).append("#")
                    .append("InputTime=").append(el.elementTextTrim("InputTime")).append("#");

            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }
        return rtbK13;

    }

    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_A19 qbp = new QRY_A19();
        qbp.initQuickstart("QRY_A19", "QRY_A19", "A");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMessageControlID().setValue(IdGenerator.getUUID());
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200230");
        msh.getMsh11_ProcessingID().getProcessingMode().setValue("QR");
        msh.getMsh11_ProcessingID().getPt2_ProcessingMode().setValue("C001");


        QRF qrf =qbp.getQRF();

        qrf.getQrf1_WhereSubjectFilter(0).setValue("RegCode");
        qrf.getQrf1_WhereSubjectFilter(1).setValue("HISPatientID");

        return qbp;
    }
}
